//
//  ChatViewController.m
//  Person
//
//  Created by kane on 14-10-18.
//  Copyright (c) 2014年 kane. All rights reserved.
//

#import "ChatViewController.h"
#import "Database.h"

#define TxtPadding 8.0

@interface ChatViewController ()<UITextViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIGestureRecognizerDelegate>
{
    __weak IBOutlet UITableView *chatTable;
    __weak IBOutlet UIView *contentView;
    __weak IBOutlet UIView *inputView;
    __weak IBOutlet UITextView *inputTV;
    
    NSMutableArray *dataList;
    NSMutableArray *viewList;
}

@end

@implementation ChatViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    dataList = [[NSMutableArray alloc] init];
    viewList = [[NSMutableArray alloc] init];
 
    [inputTV drawBorderColor:[UIColor lightGrayColor] Width:1];
    [inputTV drawCornerRadius:5];
    
    [self registerForKeyboardNotification];
    [self loadLocalData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)tapGesture:(id)sender
{
    [self.view endEditing:YES];
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    return inputTV.isFirstResponder;
}

- (void)loadLocalData
{
    [dataList removeAllObjects];
    [viewList removeAllObjects];
    //获取本地数据
    NSDictionary *msgDic = @{@"sendtime":[[NSString stringWithFormat:@"%@",[NSDate date]] substringToIndex:16],@"text":@"Hi~你好，我是客服小牙妹~\n😊有什么可以帮到你的呢？"};
    [dataList addObject:msgDic];
    [viewList addObject:msgDic];
    NSArray *ary = [[NSUserDefaults standardUserDefaults] objectForKey:@"chatList"];
    [dataList addObjectsFromArray:ary];
    [viewList addObjectsFromArray:ary];
    
    [chatTable reloadData];
    if ([dataList count] > 0) {
        [chatTable scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[dataList count]-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }
    [self.view endEditing:YES];
}

- (void)registerForKeyboardNotification{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasHidden:) name:UIKeyboardWillHideNotification object:nil];
}



#pragma mark - UIButton Events

- (IBAction)backBtnPressed:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)sendBtnPressed:(id)sender {
    if (inputTV.text.length == 0) {
        return;
    }
    [self sendTextMessage:inputTV.text];
    inputTV.text = @"";
    inputView.frame = CGRectMake(inputView.frame.origin.x, contentView.frame.size.height - 44, inputView.frame.size.width, 44);
}

- (void)sendTextMessage:(NSString *)text
{
    NSDictionary *msgDic = @{@"sendtime":[[NSString stringWithFormat:@"%@",[NSDate date]] substringToIndex:16],@"text":text};
    NSArray *ary = [[NSUserDefaults standardUserDefaults] objectForKey:@"chatList"];
    NSMutableArray *dataAry = [NSMutableArray arrayWithArray:ary];
    [dataAry addObject:msgDic];
    [[NSUserDefaults standardUserDefaults] setObject:dataAry forKey:@"chatList"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [self loadLocalData];
}


#pragma mark - UITableView DataSource && Delegate

//组装对话框
- (UIView *)bubbleViewByInfo:(NSDictionary *)info indexPath:(NSIndexPath *)indexPath
{
	// build single chat bubble cell with given text
    BOOL sendOut = indexPath.row > 0;
    CGFloat width = chatTable.frame.size.width * 0.7;
    
	UIView *returnView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, chatTable.frame.size.width, 60)];
	returnView.backgroundColor = [UIColor clearColor];
    
    //头像
    UIImageView *headImageView = [[UIImageView alloc] init];
    headImageView.image = [UIImage imageNamed:sendOut?@"image_MVHealthNewsBtn":@"wbicon"];
    headImageView.frame = CGRectMake(sendOut ? 260 : 10, 10, 40, 40);
    [returnView addSubview:headImageView];
    
    //时间
    UILabel *timeLbl = [[UILabel alloc] initWithFrame:CGRectMake(0, headImageView.frame.origin.y, chatTable.frame.size.width - headImageView.frame.size.width * 2 - 30 , 20)];
    timeLbl.backgroundColor = [UIColor clearColor];
    timeLbl.font = [UIFont systemFontOfSize:13];
    timeLbl.textAlignment = sendOut ? NSTextAlignmentRight : NSTextAlignmentLeft;
    timeLbl.text = [[info objectForKey:@"sendtime"] substringWithRange:NSMakeRange(10, 6)];
    [returnView addSubview:timeLbl];
    timeLbl.center = CGPointMake(returnView.center.x, timeLbl.center.y);
    
    //文字背景框
    UIView *txtBgView = [[UIView alloc] initWithFrame:CGRectZero];    
    txtBgView.backgroundColor = sendOut ? [UIColor greenColor]:[UIColor colorWithRed:242/255.f green:242/255.f blue:242/255.f alpha:1.0];
    txtBgView.layer.cornerRadius = 5;
    [txtBgView.layer masksToBounds];
    
    //文字
    UILabel *textLbl = [[UILabel alloc] initWithFrame:CGRectMake(TxtPadding, TxtPadding, width, 20)];
    textLbl.backgroundColor = [UIColor clearColor];
    textLbl.numberOfLines = 0;
    textLbl.font = [UIFont systemFontOfSize:14];
    textLbl.text = [info objectForKey:@"text"];
    [txtBgView addSubview:textLbl];
    [textLbl sizeToFit];
    
    //单行情况
    if (textLbl.frame.size.height == 20) {
        textLbl.frame = CGRectMake(TxtPadding, TxtPadding, textLbl.text.length * 16, 20);
    }
    
    //背景大小
    txtBgView.frame = CGRectMake(timeLbl.frame.origin.x, timeLbl.frame.origin.y + timeLbl.frame.size.height, textLbl.frame.size.width + TxtPadding *2, textLbl.frame.size.height + TxtPadding * 2);
    if (sendOut) {
        txtBgView.center = CGPointMake(chatTable.frame.size.width - timeLbl.frame.origin.x - txtBgView.frame.size.width/2 , txtBgView.center.y);
    }
    
    [returnView addSubview:txtBgView];
    
    CGFloat hight = txtBgView.frame.origin.y + txtBgView.frame.size.height > 65 ? txtBgView.frame.origin.y + txtBgView.frame.size.height : 65;
    returnView.frame = CGRectMake(0, 0, chatTable.frame.size.width, hight + 20);
    
	return returnView;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [dataList count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *info = [dataList objectAtIndex:indexPath.row];
    UIView *itemView = [self bubbleViewByInfo:info indexPath:indexPath];
    [viewList replaceObjectAtIndex:indexPath.row withObject:itemView];
    return itemView.frame.size.height;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"ChatCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    for (UIView *subV in cell.contentView.subviews) {
        [subV removeFromSuperview];
    }
    
    UIView *itemView = [viewList objectAtIndex:[indexPath row]];
	[cell.contentView addSubview:itemView];
    
    return cell;
}

#pragma mark - UITextFieldDelegate

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"]) {
        [inputTV endEditing:YES];
        return NO;
    }
    return YES;
}

- (void)textViewDidChange:(UITextView *)textView
{
    CGRect inputFrame = inputView.frame;
    if (inputFrame.size.height != textView.contentSize.height + 10 && textView.contentSize.height < 124) {
        inputView.frame = CGRectMake(inputView.frame.origin.x, inputView.frame.origin.y - (textView.contentSize.height + 10 - inputView.frame.size.height), inputView.frame.size.width, textView.contentSize.height + 10);
    }
}

- (void)autoMoveKeyBoard:(float)height
{
    int inputY = contentView.frame.size.height - inputView.frame.size.height/2;
    int y = height == 0 ? inputY :inputY - height;
    inputView.center = CGPointMake(inputView.center.x, y);
}

- (void) keyboardWasShown:(NSNotification *) notif{
    chatTable.userInteractionEnabled = NO;
    NSDictionary *info = [notif userInfo];
    NSValue *value = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGSize keyboardSize = [value CGRectValue].size;
    float dist;
    UIInterfaceOrientation orientation=[UIApplication sharedApplication].statusBarOrientation;
    switch (orientation) {
        case UIInterfaceOrientationLandscapeLeft:
        case UIInterfaceOrientationLandscapeRight:
            dist=keyboardSize.width;
            break;
        case UIInterfaceOrientationPortraitUpsideDown:
        case UIInterfaceOrientationPortrait:
            dist=keyboardSize.height;
            break;
        default:
            dist=0;
            break;
    }
    [self autoMoveKeyBoard:dist];
    if([dataList count] > 0){
		[chatTable scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[dataList count]-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
	}
}

- (void) keyboardWasHidden:(NSNotification *) notif{
    chatTable.userInteractionEnabled = YES;
    [self autoMoveKeyBoard:0];
    if([dataList count] > 0){
		[chatTable scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[dataList count]-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
	}
}

- (NSString *)getLocalDateString:(NSDate *)anyDate
{
    NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];//或GMT
    NSTimeZone* destinationTimeZone = [NSTimeZone localTimeZone];
    NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:anyDate];
    NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:anyDate];
    NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
    NSDate* destinationDateNow = [[NSDate alloc] initWithTimeInterval:interval sinceDate:anyDate];
    
    NSString *dateString = [NSString stringWithFormat:@"%@",destinationDateNow];
    return [dateString substringToIndex:19];
}

@end
